﻿using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;


namespace WebApp
{
    public class MyAuthenticationHandler : IAuthenticationHandler, IAuthenticationSignInHandler, IAuthenticationSignOutHandler
    {
        public AuthenticationScheme AuthentictionScheme { get; private set; }

        public HttpContext HttpContext { get; private set; }
        public Task<AuthenticateResult> AuthenticateAsync()
        {
            var cookie = this.HttpContext.Request.Cookies["MyCookie"];
            if (null == cookie)
                return Task.FromResult<AuthenticateResult>(AuthenticateResult.NoResult());

            var pairs = cookie.Split(new char[] { ';' });
            var claims = new List<System.Security.Claims.Claim>();
            claims.Add(new Claim(ClaimTypes.Name, pairs[0]));
            //claims.Add(new Claim("password", pairs[1]));
            var identity = new ClaimsIdentity(authenticationType: "Username");
            identity.AddClaims(claims);

            var princle = new ClaimsPrincipal(identity);

            var ticket = new AuthenticationTicket(princle, "myScheme");
            //HttpContext.User.Identity.IsAuthenticated = true;

            var result = AuthenticateResult.Success(ticket);
            return Task.FromResult<AuthenticateResult>(AuthenticateResult.Success(ticket));
        }

        public Task ChallengeAsync(AuthenticationProperties properties)
        {
            this.HttpContext.Response.Redirect("/login");
            return Task.CompletedTask;
        }

        public Task ForbidAsync(AuthenticationProperties properties)
        {
            this.HttpContext.Response.StatusCode = 403;
            return Task.CompletedTask;
        }

        public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
        {
            this.AuthentictionScheme = scheme;
            this.HttpContext = context;
            return Task.CompletedTask;
        }


        public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
        {
            var ticket = new AuthenticationTicket(user, properties, AuthentictionScheme.Name);
            HttpContext.Response.Cookies.Append("MyCookie", "zhangsan;123");

            return Task.CompletedTask;
        }

        public Task SignOutAsync(AuthenticationProperties properties)
        {
            HttpContext.Response.Cookies.Delete("MyCookie");
            return Task.CompletedTask;
        }
    }
}
